package com.coursehub.exercise.controller;

import com.coursehub.exercise.entity.Exercise;
import com.coursehub.exercise.entity.Submission;
import com.coursehub.exercise.service.ExerciseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/exercises")
@CrossOrigin(origins = "*")
public class ExerciseController {
    
    @Autowired
    private ExerciseService exerciseService;
    
    // 作业管理API
    @PostMapping
    public ResponseEntity<Exercise> createExercise(@RequestBody Exercise exercise) {
        Exercise created = exerciseService.createExercise(exercise);
        return ResponseEntity.ok(created);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Exercise> updateExercise(@PathVariable Long id, @RequestBody Exercise exercise) {
        Exercise updated = exerciseService.updateExercise(id, exercise);
        return ResponseEntity.ok(updated);
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteExercise(@PathVariable Long id) {
        exerciseService.deleteExercise(id);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Exercise> getExerciseById(@PathVariable Long id) {
        Optional<Exercise> exercise = exerciseService.getExerciseById(id);
        return exercise.map(ResponseEntity::ok)
                      .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping
    public ResponseEntity<List<Exercise>> getAllExercises() {
        List<Exercise> exercises = exerciseService.getAllExercises();
        return ResponseEntity.ok(exercises);
    }
    
    @GetMapping("/course/{courseId}")
    public ResponseEntity<List<Exercise>> getExercisesByCourse(@PathVariable Long courseId) {
        List<Exercise> exercises = exerciseService.getExercisesByCourse(courseId);
        return ResponseEntity.ok(exercises);
    }
    
    @GetMapping("/class/{classId}")
    public ResponseEntity<List<Exercise>> getExercisesByClass(@PathVariable Long classId) {
        List<Exercise> exercises = exerciseService.getExercisesByClass(classId);
        return ResponseEntity.ok(exercises);
    }
    
    @GetMapping("/teacher/{teacherId}")
    public ResponseEntity<List<Exercise>> getExercisesByTeacher(@PathVariable Long teacherId) {
        List<Exercise> exercises = exerciseService.getExercisesByTeacher(teacherId);
        return ResponseEntity.ok(exercises);
    }
    
    @GetMapping("/type/{type}")
    public ResponseEntity<List<Exercise>> getExercisesByType(@PathVariable Exercise.ExerciseType type) {
        List<Exercise> exercises = exerciseService.getExercisesByType(type);
        return ResponseEntity.ok(exercises);
    }
    
    @GetMapping("/search")
    public ResponseEntity<List<Exercise>> searchExercisesByTitle(@RequestParam String title) {
        List<Exercise> exercises = exerciseService.searchExercisesByTitle(title);
        return ResponseEntity.ok(exercises);
    }
    
    @GetMapping("/due-between")
    public ResponseEntity<List<Exercise>> getExercisesDueBetween(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        List<Exercise> exercises = exerciseService.getExercisesDueBetween(startDate, endDate);
        return ResponseEntity.ok(exercises);
    }
    
    @GetMapping("/overdue")
    public ResponseEntity<List<Exercise>> getOverdueExercises() {
        List<Exercise> exercises = exerciseService.getOverdueExercises();
        return ResponseEntity.ok(exercises);
    }
    
    // 作业提交API
    @PostMapping("/submissions")
    public ResponseEntity<Submission> submitExercise(@RequestBody Submission submission) {
        Submission created = exerciseService.submitExercise(submission);
        return ResponseEntity.ok(created);
    }
    
    @PutMapping("/submissions/{id}")
    public ResponseEntity<Submission> updateSubmission(@PathVariable Long id, @RequestBody Submission submission) {
        Submission updated = exerciseService.updateSubmission(id, submission);
        return ResponseEntity.ok(updated);
    }
    
    @DeleteMapping("/submissions/{id}")
    public ResponseEntity<Void> deleteSubmission(@PathVariable Long id) {
        exerciseService.deleteSubmission(id);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/submissions/{id}")
    public ResponseEntity<Submission> getSubmissionById(@PathVariable Long id) {
        Optional<Submission> submission = exerciseService.getSubmissionById(id);
        return submission.map(ResponseEntity::ok)
                        .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/{exerciseId}/submissions")
    public ResponseEntity<List<Submission>> getSubmissionsByExercise(@PathVariable Long exerciseId) {
        List<Submission> submissions = exerciseService.getSubmissionsByExercise(exerciseId);
        return ResponseEntity.ok(submissions);
    }
    
    @GetMapping("/submissions/student/{studentId}")
    public ResponseEntity<List<Submission>> getSubmissionsByStudent(@PathVariable Long studentId) {
        List<Submission> submissions = exerciseService.getSubmissionsByStudent(studentId);
        return ResponseEntity.ok(submissions);
    }
    
    @GetMapping("/{exerciseId}/submissions/student/{studentId}")
    public ResponseEntity<Submission> getSubmissionByExerciseAndStudent(
            @PathVariable Long exerciseId, @PathVariable Long studentId) {
        Optional<Submission> submission = exerciseService.getSubmissionByExerciseAndStudent(exerciseId, studentId);
        return submission.map(ResponseEntity::ok)
                        .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/submissions/status/{status}")
    public ResponseEntity<List<Submission>> getSubmissionsByStatus(@PathVariable Submission.SubmissionStatus status) {
        List<Submission> submissions = exerciseService.getSubmissionsByStatus(status);
        return ResponseEntity.ok(submissions);
    }
    
    @GetMapping("/submissions/need-grading")
    public ResponseEntity<List<Submission>> getSubmissionsNeedingGrading() {
        List<Submission> submissions = exerciseService.getSubmissionsNeedingGrading();
        return ResponseEntity.ok(submissions);
    }
    
    // 评分API
    @PostMapping("/submissions/{submissionId}/grade")
    public ResponseEntity<Submission> gradeSubmission(
            @PathVariable Long submissionId,
            @RequestParam Integer score,
            @RequestParam(required = false) String feedback,
            @RequestParam Long gradedBy) {
        Submission graded = exerciseService.gradeSubmission(submissionId, score, feedback, gradedBy);
        return ResponseEntity.ok(graded);
    }
    
    @GetMapping("/{exerciseId}/submissions/graded")
    public ResponseEntity<List<Submission>> getGradedSubmissionsByExercise(@PathVariable Long exerciseId) {
        List<Submission> submissions = exerciseService.getGradedSubmissionsByExercise(exerciseId);
        return ResponseEntity.ok(submissions);
    }
    
    @GetMapping("/{exerciseId}/average-score")
    public ResponseEntity<Double> getAverageScoreByExercise(@PathVariable Long exerciseId) {
        Double averageScore = exerciseService.getAverageScoreByExercise(exerciseId);
        return ResponseEntity.ok(averageScore);
    }
    
    // 统计API
    @GetMapping("/count/teacher/{teacherId}")
    public ResponseEntity<Long> countExercisesByTeacher(@PathVariable Long teacherId) {
        long count = exerciseService.countExercisesByTeacher(teacherId);
        return ResponseEntity.ok(count);
    }
    
    @GetMapping("/count/course/{courseId}")
    public ResponseEntity<Long> countExercisesByCourse(@PathVariable Long courseId) {
        long count = exerciseService.countExercisesByCourse(courseId);
        return ResponseEntity.ok(count);
    }
    
    @GetMapping("/count/class/{classId}")
    public ResponseEntity<Long> countExercisesByClass(@PathVariable Long classId) {
        long count = exerciseService.countExercisesByClass(classId);
        return ResponseEntity.ok(count);
    }
    
    @GetMapping("/{exerciseId}/submissions/count")
    public ResponseEntity<Long> countSubmissionsByExercise(@PathVariable Long exerciseId) {
        long count = exerciseService.countSubmissionsByExercise(exerciseId);
        return ResponseEntity.ok(count);
    }
    
    @GetMapping("/submissions/count/student/{studentId}")
    public ResponseEntity<Long> countSubmissionsByStudent(@PathVariable Long studentId) {
        long count = exerciseService.countSubmissionsByStudent(studentId);
        return ResponseEntity.ok(count);
    }
    
    @GetMapping("/{exerciseId}/submissions/graded/count")
    public ResponseEntity<Long> countGradedSubmissionsByExercise(@PathVariable Long exerciseId) {
        long count = exerciseService.countGradedSubmissionsByExercise(exerciseId);
        return ResponseEntity.ok(count);
    }
    
    @GetMapping("/{exerciseId}/student/{studentId}/submitted")
    public ResponseEntity<Boolean> hasStudentSubmitted(@PathVariable Long exerciseId, @PathVariable Long studentId) {
        boolean hasSubmitted = exerciseService.hasStudentSubmitted(exerciseId, studentId);
        return ResponseEntity.ok(hasSubmitted);
    }
}